package com.MinesweeperGame.client;

import java.util.HashMap;

import com.MinesweeperGame.client.MinesweeperGame.MinesweeperButton;



public class MinesweeperBackground {
	
        private boolean _mineGrid[][];
		
		private int _numberGrid[][];
		
		private int _rows;
		
		private int _cols;
		
		private int _mines;
		
		HashMap< String, MinesweeperButton> mineMap = 
				new HashMap<String, MinesweeperGame.MinesweeperButton>();
		
		public MinesweeperBackground(int rows, int cols){
			
			_mineGrid = new boolean[rows][cols];
			_numberGrid = new int[rows][cols];
			
			_rows = rows;
			_cols = cols;
			
			if(cols == 16){
				_mines = 40;
			}
			
			if(cols == 10){
				_mines = 10;
			}
			
			if(cols == 30){
				_mines = 99;
			}
			
			for( ; _mines > 0 ;){
				
				int i = getRandomNumber(rows);
				int j = getRandomNumber(cols);
				
				if(_mineGrid[i][j] == true)
					continue;
				
				_mineGrid[i][j] = true;
				
				_mines--;
			}
			
			for( int i = 0 ; i < rows ; i++ ){
				
				for( int j = 0 ; j < cols ; j++ ){
					
					_numberGrid[i][j] = getMines(_mineGrid, i, j, rows, cols);
					
				}
			}
		}
		
		public int[][] getNumberArray(){
			return _numberGrid;
		}
		
		public boolean[][] getMineArray(){
			return _mineGrid;
		}
		
		
		public boolean getIsMine(int i , int j){
			
			if(i < 0)
				return false;
			
			if(i > _rows){
				return false;
			}
			
			if(j < 0)
				return false;
			
			if(j > _cols){
				return false;
			}
			
			return _mineGrid[i][j];
// gets the mines.
			
		}
		
		public int getMineCount(int i , int j){
			if(i < 0)
				return -1;
			
			if(i > _rows){
				return -1;
			}
			
			if(j < 0)
				return -1;
			
			if(j > _cols){
				return -1;
			}
			
			return _numberGrid[i][j];
		}
		
		public int getMines(boolean[][] mineField, int i, int j, int rows, int cols){
			
			
			int x = 0;
			int y = 0;
			
			int xMax = i + 1;
			int yMax = j + 1;
			
			
			if(i > 0){
				x = i - 1;
			}
			
			if( xMax > rows - 1){
				xMax = rows - 1;
			}
			
			if( j > 0 ){
				y = j - 1;
			}
			
			if(yMax > cols - 1){
				yMax = cols - 1;
			}
			
			int mines = 0;
			
			for( ; x <= xMax ; x++){
				for(y = (j > 0)?j - 1:0 ; y <= yMax ; y++ ){
						
					if(mineField[x][y])
						mines++;
				}
			}
			
			return mines;
			
		}
		
		
		private int getRandomNumber(int maxValue){
			
			double generatedRandom = Math.random();
			
			if(maxValue <= 10)
				generatedRandom = generatedRandom * 10;
			else{
				
				for(;;){
					
					generatedRandom = Math.random();
					
					generatedRandom = generatedRandom * 100;
					
					if(generatedRandom < maxValue)
						break;
				}
			}
			
			return (int)generatedRandom;
		}
		
	}



